package com.ruoyi.sale.auditStatusMachine.impl;

import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.mapper.AuditMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.sale.auditStatusMachine.StatusService;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.domain.SaleorderModel;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.sale.mapper.SaleorderMapper;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.domain.WarehousingRecords;
import com.ruoyi.warehousing.mapper.WarehousingMapper;
import com.ruoyi.warehousing.mapper.WarehousingRecordsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 销货单 回退
 * @Author Mr.Yi.Zhang
 * @Version 1.0
 */
@Component
public class Rollback implements StatusService {

    private static final String FLAG = "0";

    @Override
    public String get() {
        return FLAG;
    }

    /** 销货单Mapper */
    @Autowired
    private SaleGoodsMapper saleGoodsMapper;
    /** 产品库存mapper */
    @Autowired
    private WarehousingMapper warehousingMapper;
    /** 产品库存操作记录Mapper */
    @Autowired
    private WarehousingRecordsMapper warehousingRecordsMapper;
    /** 销售审核Mapper */
    @Autowired
    private AuditMapper auditMapper;
    /** 销售订单 **/
    @Autowired
    private SaleorderMapper saleOrderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int execute(SaleGoodsOrder order) {
        // 同步库存
        // 获取销货单的产品列表
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("deptId",SecurityUtils.getDeptId());
        queryParams.put("saleGoodsId", order.getSaleorderId());
        SaleGoodsOrder saleGoodsOrder = saleGoodsMapper.selectSaleGoodsById(queryParams);

        // 是否已有退货
        if ("1".equals(saleGoodsOrder.getIsReturn())) {
            throw new RuntimeException("该订单已有退货,不允许退回审核");
        }

        // 查看该销货单对应的销售订单是否存在发票
        List<Long> saleGoodsModelIds = saleGoodsOrder.getSaleGoodsModels().stream()
                .map(SaleGoodsModel::getSaleGoodsModelId)
                .collect(Collectors.toList());
        List<SaleGoodsModel> saleGoodsModelsResult = saleGoodsMapper.selectSaleGoodsModelByListsInvoice(saleGoodsModelIds);
        if (!saleGoodsModelsResult.isEmpty()) {
            throw new RuntimeException("该订单已有开票信息,不允许退回审核");
        }

        saleGoodsOrder.setSaleGoodsStatus(order.getSaleGoodsStatus());
        saleGoodsOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());

        // 增加库存
        List<SaleGoodsModel> saleGoodsModels = saleGoodsOrder.getSaleGoodsModels();
        if (!saleGoodsModels.isEmpty()) {
            WarehousingRecords warehousingRecords = new WarehousingRecords();
            for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
                int num = saleGoodsModel.getAllNum();
                //找库存表 获取id
                Warehousing warehousing = new Warehousing();
                warehousing.setSelectId(saleGoodsModel.getProductId());
                warehousing.setDeptId(saleGoodsOrder.getDeptId());
                warehousing.setProductId(saleGoodsModel.getProductId());
                warehousing.setProductType(saleGoodsModel.getProductType());
                warehousing.setBatch(saleGoodsModel.getBatch());
                Warehousing warehousing1 = warehousingMapper.selectWarehousing(warehousing);
                //存储本次减少的数量
                warehousingRecords.setInventoryNum(-saleGoodsModel.getNum());
                warehousingRecords.setAllnum(saleGoodsModel.getAllNum());
                //判断是否拥有该公司该产品该型号名称的库存记录
                if (warehousing1 != null) {
                    //int warehousingNum = warehousing1.getWarehousingNum();
                    Long warehousingNum = warehousing1.getAmount();
                    //int warehousingNum = warehousing1.getWarehousingNum();

                    Long num1 = num + warehousingNum;
                    warehousing.setAmount(num1);
                    warehousing.setWarehousingId(warehousing1.getWarehousingId());
                    if (warehousing.getAmount() < 0) {
                        new AjaxResult(AjaxResult.Type.ERROR, "库存不足");
                        throw new RuntimeException("库存不足");
                    }
                    warehousingMapper.updateWarehousing(warehousing);
                } else {
                    new AjaxResult(AjaxResult.Type.ERROR, "没有找到该型号的数据，请确定是否有该型号库存");
                    throw new RuntimeException("没有找到该型号的数据，请确定是否有该型号库存");
                }
                warehousingRecordsMapper.deleteWarehousingRecords(saleGoodsOrder.getSaleGoodsNum());
            }
        }

        // 同步销售审核状态
        Audit auditQueryParams = new Audit();
        auditQueryParams.setOrderId(order.getSaleorderId());
        // 获取销货单 类型
        auditQueryParams.setOrderType("3");
        Audit audit = auditMapper.selectAuditByOrderId(auditQueryParams);
        audit.setAuditStatus(saleGoodsOrder.getSaleGoodsStatus());
        auditMapper.updateAudit(audit);

        // 同步销货单状态
        int result = saleGoodsMapper.auditSale(order);

        // 根据 销售订单 的 订单号 获取 销售订单 的 订单ID
        String saleOrderId = saleOrderMapper.querySaleOrderIdBySaleOrderNum(saleGoodsOrder.getWuliunumber());
        // 根据 销售订单 的 订单ID 获取 销售订单 中的 产品出库列表
        List<SaleorderModel> saleOrderModels = saleOrderMapper.selectSaleModelBySaleOrderId(saleOrderId);
        // 对 销货单 中的 产品出库列表 进行 分组
        Map<Long, List<SaleGoodsModel>> groupSaleGoodsModelBySaleOrderModelId = saleGoodsModels.stream()
                .collect(Collectors.groupingBy(SaleGoodsModel::getSaleorderModelId));
        // 计算 销售订单 的 未出库 数量. 已出库数量
        saleOrderModels.forEach(saleOrderModel -> {
            // 获取 销售单 对应的 销货单 中的 产品 出库数量
            Long saleOrderModelId = saleOrderModel.getSaleorderModelId();
            List<SaleGoodsModel> models = groupSaleGoodsModelBySaleOrderModelId.get(saleOrderModelId);
            if (null !=  models && !models.isEmpty()) {
                int outNum = models.stream().map(SaleGoodsModel::getRemainingNum).filter(Objects::nonNull).mapToInt(Integer::intValue).sum();
                // 计算销售订单剩余出库数量
                saleOrderModel.setRemainingNum(saleOrderModel.getRemainingNum() + outNum);
                // 计算销售订单已出库数量
                saleOrderModel.setExecuteNum(saleOrderModel.getExecuteNum() - outNum);
            }
        });
        // 修改销售订单的出库列表的出库数量
        saleOrderMapper.batchUpdateRemainingNumBySaleOrderModelId(saleOrderModels);
        return result;
    }
}
